<?php
namespace app\admin\controller\develop;
use app\admin\controller\Controller;
use app\common\model\divide\Receive as ReceiveModel;
use app\admin\model\user\User as UserModel;
use app\common\model\user\BalanceLog;
use think\Db;

/**
 * 用户分红记录
 * Class System
 * @package app\admin\controller\abonus
 */
class User extends Controller
{

    /**
     * @return string
     */
    public function index()
    {
        $model = new ReceiveModel();
        return $this->fetch('index', [
            // 充值记录列表
            'list' => $list = $model->getAllList($this->request->param()),
            // 属性集
            'statusList' => $model::getStatuslist(),

        ]);
    }

    public function detail($id=null){
        $model = new ReceiveModel();
        $extend=db('divide_receives_user')->where('receives_id',$id)->value('extend');
        $list=json_decode($extend,true);
        return $this->fetch('detail',  [
            // 充值记录列表
            'data' =>$data=$model->getList($id),
            // 属性集
            'list' =>$list
            ]);
    }

    /**
     *  将用户出局
     * @param $receives_id
     * @param $type 1.出局转零钱 2.直接出局，
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function recovery($receives_id){
        $model=new ReceiveModel();
        $receives=$model->find($receives_id);
        $reault =$model->where('receives_id',$receives_id)->setField(['type'=>1,'balance'=>0,'times '=>Db::raw('times + 1'),'small_change'=>$receives['balance']]);
        if ($reault) {
            //给用户加上零钱和添加零钱转化记录
            $this->setUserBlance($receives);
            //写入附表的转化记录
            $this->setReceivesUserAccounts($receives);
            return $this->renderSuccess('操作成功');
        }

        return $this->renderError('操作失败');
    }

    /**
     *  直接将用户出局，不转零钱
     * @param $receives_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function finish($receives_id){
        $model=new ReceiveModel();
        $receives=$model->find($receives_id);
       // $reault =$model->where('receives_id',$receives_id)->setField(['type'=>1,'balance'=>0,'times '=>Db::raw('times + 1'),'small_change'=>$receives['balance']]);
        $reault =$model->where('receives_id',$receives_id)->setField(['type'=>1]);
        if ($reault) {
            //写入附表的转化记录
           // $this->setReceivesUserAccounts($receives);
            return $this->renderSuccess('操作成功');
        }

        return $this->renderError('操作失败');
    }

    /**
     *   * 将用户多余的零钱给用户加上
     * @param $item  int  订单
     * @throws \think\Exception
     */
    private function setUserBlance($item){
        $userModel=new UserModel();
        $res=$userModel->where('user_id',$item['user_id'])->setInc('balance',$item['balance']);
        if($res){
            // 用户余额变动明细
            BalanceLog::add(50, [
                'user_id'  =>$item['user_id'],
                'money'    =>+$item['balance'],
                'wxapp_id' =>$item['wxapp_id'],
            ], ['order_no' =>$item['order_no']]);
            return $res;
        }

    }

    /**
     * 将每次的流水写入记录
     * @param $receives
     * @return int|string
     */
    private function setReceivesUserAccounts($receives){

        $extend[]=[
                'type' =>3,//退款类型 1.微信现金退款 2.赏金退款 3.零钱退款
                'refund_id'=>0, //微信内部退款订单号
                'refund_fee'=>$receives['balance'],//退款金额
                'money'=>0,//本次订单支付金额
                'order_no'=>0,//产生退款的订单编号
                'status'=>1,    //退款状态 1.退款成功
                'time' =>time()
            ];
            $extends=db('divide_receives_user')->where('receives_id',$receives['receives_id'])->value('extend');
            if($extends){
                $data = json_decode($extends, true);
                //最后一个数组
                $lastData=end($data);

                if(!isset($lastData['times'])){
                    $extend[0]['times']=1;
                }else{
                    $extend[0]['times']=$lastData['times']+1;
                }
                $json =array_merge($data,$extend);
                $res = json_encode($json );

                return db('divide_receives_user')->where('receives_id',$receives['receives_id'])->setField('extend',$res);
            }else{
                $userListData['receives_id']     =$receives['id'];//主表id
                $userListData['extend']=json_encode([[
                    'type' =>3,//退款类型 1.微信现金退款 2.赏金退款 3.零钱退款
                    'refund_id'=>0, //微信内部退款订单号
                    'refund_fee'=>$receives['balance'],//退款金额
                    'money'=>0,//本次订单支付金额
                    'order_no'=>0,//产生退款的订单编号
                    'status'=>1,    //退款状态 1.退款成功
                    'times' =>1,//第几次退款
                    'time' =>time()]]);
                $userListData['create_time']     = time();//写入时间（支付时间）
                return db('divide_receives_user')->insert($userListData);
            }
    }

}

